using SrBBSPro.Util;
using SrBBSPro.Services;
using SrBBSPro.BaseClasses;
using SrBBSPro.Entities;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.ComponentModel;
using System.Reflection;
using System.Web.Mvc;

namespace SrBBSPro.BaseClasses
{
    [Authorize]
    public class BaseController : Controller
    {       
        /// <summary>
        /// 每页显示的数据数
        /// </summary>
        protected int PageSize
        {
            get
            {
                var pageSize = ConfigurationManager.AppSettings["PageSize"];
                return pageSize == null ? 30 : Convert.ToInt32(pageSize);
            }
        }
        /// <summary>
        /// 是否已登录
        /// </summary>
        /// <returns></returns>
        protected bool IsLogin
        {
            get
            {
                return HttpContext.User.Identity.IsAuthenticated;
            }
        }
        /// <summary>
        /// 当前登录的帐户
        /// </summary>
        protected string CurrentAccount
        {
            get
            {
                if (!HttpContext.User.Identity.IsAuthenticated)
                    return "";
                var name = HttpContext.User.Identity.Name;
                var staffNo = name.Split('$')[1];
                return staffNo;
            }
        }
        /// <summary>
        /// 当前登录的用户ID
        /// </summary>
        protected string CurrentUserId
        {
            get
            {
                if (!HttpContext.User.Identity.IsAuthenticated)
                    return string.Empty;
                var name = HttpContext.User.Identity.Name;
                var userId = name.Split('$')[0];
                return userId;
            }
        }

        public long EntId
        {
            get => Convert.ToInt64(Session["Id"]);          
            set => Session["Id"] = value;           
        }

        public string EntNo
        {
            get => Session["No"] as string ?? "";
            set => Session["No"] = value;
        }

        public string EntKind
        {
            get => Session["Kind"] as string ?? "";
            set => Session["Kind"] = value;
        }

        public object GetObjByName(string name)
            => Assembly.GetExecutingAssembly().CreateInstance("SrBBSPro.Entities." + name);
   
        //登录后的头部信息
        public PartialViewResult HeaderForLogIn()
        {
            var user = new UserService().GetUserInfo(CurrentUserId);
            return PartialView("_HeaderForLogIn", user);
        }
        //最近热帖Top15
        [AllowAnonymous]
        public PartialViewResult LoadHotPostTopFifty()
        {
            var response = new PostService().GetHotPostsTopFifteen();
            return PartialView("_HotPost", response);
        }
        //近期热议Top15
        [AllowAnonymous]
        public PartialViewResult LoadHotCommentTopFifty()
        {
            var response = new PostService().GetHotCommentPostsTopFifteen();
            return PartialView("_HotComment", response);
        }
        #region Return Data
        protected Dictionary<string, object> GetResult(bool success, string message, object data = null)
        {
            return DataHelper.GetResult(success, message, data);
        }
        protected ActionResult JsonResult(bool success, string message, object data = null)
        {
            return Json(GetResult(success, message, data), JsonRequestBehavior.AllowGet);
        }
        protected ActionResult JsonResult(bool success, string message, JsonRequestBehavior behavior, object data = null)
        {
            return Json(GetResult(success, message), behavior);
        }
        protected ActionResult JsonResult(bool success, string message, object data, JsonRequestBehavior behavior)
        {
            return Json(GetResult(success, message, data), behavior);
        }
        protected ActionResult JsonResultForFly(int status, string msg)
        {
            return Json(DataHelper.GetResult(status, msg),JsonRequestBehavior.AllowGet);
        }
        protected ActionResult JsonResultForFly(int status, string msg,string action)
        {
            return Json(DataHelper.GetResult(status, msg, action));
        }
        protected ActionResult JsonResultForFly(int status, string msg, object rows)
        {
            return Json(DataHelper.GetResult(status, msg, rows));
        }
        protected ActionResult JsonResultForFly(int status, string msg, object rows, string code)
        {
            return Json(DataHelper.GetResult(status, msg, rows, code));
        }
        protected ActionResult JsonResultForFly(int status, string msg, Dictionary<string,object> dict)
        {
            return Json(DataHelper.GetResult(status, msg, dict));
        }

        protected ActionResult JsonResultForLay<T,TID>(List<T> li, int count=0 ,bool IsSkill=true) where T : BaseEntity<TID>
        {
            return Json(DataHelper.GetResult<T, TID>(li , count,IsSkill), JsonRequestBehavior.AllowGet);
        }

        protected ActionResult JsonResultForLay<T>(List<T> li) 
        {
            return Json(DataHelper.GetResult(li), JsonRequestBehavior.AllowGet);
        }

        protected ActionResult JsonResultForLay<T>(T t) where T : BaseUserEntity
        {
            var dic = new List<Dictionary<string, object>>();              
            foreach (var prop in t.GetType().GetProperties())
            {
                if (prop.Name.Equals("User"))
                    continue;
                var val = prop.GetValue(t);
                object[] obs = prop.GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (val != null && val.GetType() == typeof(DateTime))
                {
                    var map = new Dictionary<string, object>();
                    if (obs.Length > 0)
                    {
                        var des = obs[0] as DescriptionAttribute;
                        map.Add("des", des.Description);
                    }
                    else
                    {
                        map.Add("des", prop.Name);
                    }
                    map.Add("val", Convert.ToDateTime(val).ToString("yyyy/MM/dd"));
                    map.Add("txt", prop.Name);
                    dic.Add(map);
                }
                else
                {
                    var map = new Dictionary<string, object>();
                    if (obs.Length > 0)
                    {
                        var des = obs[0] as DescriptionAttribute;
                        map.Add("des", des.Description);
                    }
                    else
                    {
                        map.Add("des", prop.Name);
                    }
                    map.Add("val", val);
                    map.Add("txt", prop.Name);
                    dic.Add(map);
                }
            }
            return Json(new { status = 0, msg = dic });
        }


        public ActionResult JsonResultOption(List<string> li)
        {
            var dic = new Dictionary<string, string>();
            foreach(var item in li)
            {
                dic.Add(item, item);
            }
            return Json(DataHelper.GetResult(dic));
        }

        public ActionResult JsonResultForLay(string name)
        {
            var obj = GetObjByName(name);
            if (obj != null)
            {
                var dic =new Dictionary<string, string>();
                foreach (var prop in obj.GetType().GetProperties())
                {
                    if (prop.Name.Equals("Id")  || prop.Name.Equals("User"))
                        continue;
                    object[] obs = prop.GetCustomAttributes(typeof(DescriptionAttribute), false);
                    if (obs.Length > 0)
                    {
                        var des = obs[0] as DescriptionAttribute;
                        dic.Add(prop.Name, des.Description);
                    }
                    else
                    {
                        dic.Add(prop.Name, prop.Name);
                    }
                }
                return Json(DataHelper.GetResult(dic));
            }
            else
            {
                return Json(new { status = 1, msg = "请求异常" });
            }
        }
        #endregion
    }
}